<?php

namespace App\Service\Third;

use App\Constants\ErrorCode;
use App\Exception\ApiException;
use App\Model\Message;
use App\Model\VideoCall;
use App\Model\VideoCallAudit;
use App\Model\VideoCallAuditConfig;
use App\Model\VideoCallAuditLog;
use App\Service\BaseService;

class SMVideoCallCallbackService extends BaseService
{
    public function handle()
    {
        if ((new VideoCallAuditConfig())->isEnableAudit() === false) {
            return ['msg' => 'success'];
        }

        $callbackArray = $this->request->all();

        log_info(__CLASS__ . "==callbackArray:" . json_encode($callbackArray, JSON_UNESCAPED_UNICODE));

        if (!isset($callbackArray['code']) || $callbackArray['code'] != 200) {
            log_info(__CLASS__ . "==callbackArray:" . json_encode($callbackArray, JSON_UNESCAPED_UNICODE));

            throw new ApiException('回调数据错误', ErrorCode::DEFAULT_ERROR);
        }

        if ($callbackArray['results']['porn']['scene'] != 'porn' || $callbackArray['suggestion'] != 'block') {
            return ['msg' => 'success'];
        }

        $videoCall = VideoCall::where(['channel_id' => $callbackArray['channelName']])->first();

        // 挂断消息
        Message::sendSlient($videoCall['user_id'], 'VIDEO_YELLOW_TIP', [
            'time' => 5,
            'tip'  => '系统鉴别视频中存在违规内容，通话',
            'endtip' => 's后将被挂断！',
        ]);
        // 挂断消息
        Message::sendSlient($videoCall['chat_user_id'], 'VIDEO_YELLOW_TIP', [
            'time' => 5,
            'tip'  => '系统鉴别视频中存在违规内容，通话',
            'endtip' => 's后将被挂断！',
        ]);

        // 添加违规审核记录
        (new VideoCallAuditLog())->addAuditLog($callbackArray['channelName'], $callbackArray['requestId'], '', '', json_encode($callbackArray, JSON_UNESCAPED_UNICODE));

        return ['msg' => 'success'];
    }
}
